package com.demo.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;


/**
 * 
 * @Title: BaseServiceImpl.java
 * @Package cn.itcast.shop.service.impl
 * @Description: TODO(用来抽取和实现公共的业务逻辑代码)
 * @author QQ495663075
 * @date 2014-4-27 上午9:39:19
 * @version V1.0
 */
@Repository("baseDao")
@Lazy(true)
@SuppressWarnings("unchecked")
public class BaseDaoImpl<T> implements com.demo.dao.BaseDao<T> {
	// 当前的T类型
	private Class clazz=null;
	
	public BaseDaoImpl(){
		System.out.println("当前子类对象:" + this);
		System.out.println("获取当前this对象相应的类型:" + this.getClass());
		System.out.println("获取当前类型的父类型信息(并不包括父类型参数信息):" + this.getClass().getSuperclass());
		System.out.println("获取当前类型的父类型信息(包括父类型参数信息):" + this.getClass().getGenericSuperclass());
		ParameterizedType type=(ParameterizedType)this.getClass().getGenericSuperclass();
		clazz=(Class)type.getActualTypeArguments()[0];
		System.out.println(clazz);
	}

	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(T t) {
		getSession().save(t);
	}

	@Override
	public int delete(String id) {
		String hql = "DELETE FROM " + clazz.getSimpleName() + " WHERE id=:id";
		return getSession().createQuery(hql) //
				.setString("id", id)//
				.executeUpdate();
	}

	@Override
	public void update(T t) {
		try {
			getSession().update(t);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<T> query() {
		String hql = "FROM " + clazz.getSimpleName();
		return getSession().createQuery(hql).list();
	}

	@Override
	public T get(String id) {
		String hql = "FROM " + clazz.getSimpleName() + " WHERE id=:id";
		return (T) getSession().createQuery(hql) //
				.setString("id", id)//
				.uniqueResult();
	}

	@Override
	public List<T> query(String hql) {
		return getSession().createQuery(hql).list();
	}
}
